package com.itheima.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.pinda.base.entity.Entity;
import com.itheima.pinda.utils.DateUtils;
import com.itheima.wms.common.service.CrudServiceImpl;
import com.itheima.wms.dao.StatusRecordMapper;
import com.itheima.wms.entity.StatusRecordEntity;
import com.itheima.wms.service.StatusRecordService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 业务实现类
 * 状态记录
 * </p>
 */
@Slf4j
@Service
public class StatusRecordServiceImpl extends CrudServiceImpl<StatusRecordMapper, StatusRecordEntity> implements StatusRecordService {

    @SneakyThrows
    @Override
    public <M extends Entity> void saveStatus(M entity) {
        Class<M> mClass = (Class<M>) entity.getClass();
        Method idMethod = mClass.getMethod("getId");
        Long id = (Long) idMethod.invoke(entity);
        Method statusMethod = mClass.getMethod("getStatus");
        Integer status = (Integer) statusMethod.invoke(entity);

        StatusRecordEntity statusRecordEntity = new StatusRecordEntity();
        statusRecordEntity.setBusinessId(id);
        statusRecordEntity.setBusinessModel(mClass.getName());
        statusRecordEntity.setBusinessType(mClass.getSimpleName());
        statusRecordEntity.setBusinessStatus(status.toString());
        statusRecordEntity.setHappenTime(LocalDateTime.now());
        this.save(statusRecordEntity);
    }

    @Override
    public List<String> listTime(Long id) {
        LambdaQueryWrapper<StatusRecordEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StatusRecordEntity::getBusinessId, id);
        List<StatusRecordEntity> statusRecordEntities = this.list(wrapper);
        return statusRecordEntities.stream().map(item -> DateUtils.format(item.getHappenTime(), "yyyy-MM-dd HH:mm:ss")).collect(Collectors.toList());
    }
}

